package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.Book;
import com.winning.pmph.entity.BookArticle;
import com.winning.pmph.entity.ReleasedKnowledge;
import com.winning.pmph.service.BookArticleService;
import com.winning.pmph.service.BookService;
import com.winning.pmph.service.ReleasedKnowledgeService;
import com.winning.pmph.service.RestHighLevelService;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.Const;
import com.winning.pmph.utils.ExecutorServiceFactory;
import com.winning.pmph.vo.EsArticle;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(value = "知识资源管理/文章搜索")
@RestController
@RequestMapping("/pmph/action/esArticle")
public class EsArticleCtrl {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private RestHighLevelService restHighLevelService;
    @Resource
    private BookService bookService;
    @Resource
    private BookArticleService bookArticleService;

    /**
     * 知识搜索page;
     */
    @ApiOperation(value = "selectPage", notes = "搜索页面")
    @GetMapping("selectPage")
    public Page<EsArticle> selectPage(String keywords, String bookId, int currentPage, int pageSize) {
        Page<EsArticle> result = new Page<>(currentPage, pageSize);
        result.setRecords(new ArrayList<>());
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder titleFuzzyQuery = QueryBuilders.fuzzyQuery("title", keywords);
        MatchQueryBuilder contentMatchQuery = QueryBuilders.matchQuery("unitContent", keywords);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(bookId)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("bookId", bookId));
        }
        boolQueryBuilder.should(titleFuzzyQuery)
                .should(contentMatchQuery);
        sourceBuilder.query(boolQueryBuilder).from((currentPage - 1) * pageSize).size(pageSize);
        searchRequest.indices(Const.ES_ARTICLE_INDEX).source(sourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
            result.setTotal(searchResponse.getHits().getTotalHits());
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                EsArticle esArticle = JSON.parseObject(hit.getSourceAsString(), EsArticle.class);
                result.getRecords().add(esArticle);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    @ApiOperation(value = "initEsArticle", notes = "initEsArticle")
    @GetMapping("/initEsArticle")
    public void initEsArticle() {
        List<Book> bookList = bookService.list();
        for (Book book : bookList) {
            List<BookArticle> list = bookArticleService.lambdaQuery()
                    .eq(BookArticle::getBookId, book.getId()).list();
            for (BookArticle bookArticle : list) {
                EsArticle esArticle = JSON.parseObject(JSON.toJSONString(bookArticle), EsArticle.class);
                esArticle.setBookName(book.getName());
                esArticle.setType(EsArticle.TYPE_BOOK);
                restHighLevelService.insertEsArticle(esArticle);
            }
        }
    }
}
